//
//  AppDelegate.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/11/21.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "LoginViewController.h"
#import "UserViewModel.h"
#import "BaseNavigationController.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WXApi.h>
// 引入JPush功能所需头文件
#import "JPUSHService.h"

#import "HomeViewController.h"

#import "MyMessageListVC.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
@interface AppDelegate ()<JPUSHRegisterDelegate,WXApiDelegate>
/** <#note#> */
@property (nonatomic, strong) UIApplication *myApplication;

/** <#note#> */
@property (nonatomic, strong) NSDictionary *myLaunchOptions;


@property (nonatomic, assign) NSInteger tag;
@end


//static NSString *appKey = @"9100c310d6174e23fb741a20";
static NSString *channel = @"Your_channel_identifier";
static NSString *appKey = @"9100c310d6174e23fb741a20";

@implementation AppDelegate

//NSString * const AlipayDidSuccessNotification = @"AlipayDidSuccessNotification";
//
//NSString * const AlipayDidFailNotification = @"AlipayDidFailNotification";
//
//
//NSString * const WXApiDidSuccessNotification = @"WXApiDidSuccessNotification";
//
//NSString * const WXApiDidFailNotification = @"WXApiDidFailNotification";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    
    NSLog(@"555555555555555");
    
    self.myApplication = application;
    
    self.myLaunchOptions = launchOptions;
    //微信支付
    [WXApi registerApp:@"wx14f5e4bd4878af06"];
    
    [SVProgressHUD setMaximumDismissTimeInterval:2.0];
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    
//    [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, 0)];
//    [self performSelector:@selector(setupHuanXing) withObject:nil afterDelay:2.0];
//    [SVProgressHUD showInfoWithStatus:@"fdsfds"];
    [self setupJPUSHWithDic:launchOptions];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    self.window.backgroundColor = [UIColor whiteColor];
    
    self.window.rootViewController = [self loadMainViewController];
    
    [self.window makeKeyAndVisible];
    
    
    
    NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    
    self.tag = 0;
    if (remoteNotification)
    {
        
        if (myViewModel.userIsLogin) {
            
            self.tag = 1;
            
            [[NSUserDefaults standardUserDefaults]setObject:@"message" forKey:@"jpush"];

        }
        
      
        
        
    }
    
    return YES;
}

- (UIViewController *)loadMainViewController{
    
    myViewModel.hideShopping = YES;
    
    return   [[BaseTabBarController alloc]init];

    
//        UserViewModel *userModel = [UserViewModel shareUserViewModel];
//
//        if (userModel.userIsLogin) {
//
//             return [[BaseTabBarController alloc]init];
//
//        }else{


//            return   [[BaseNavigationController alloc]initWithRootViewController:[[LoginViewController alloc]init]];

//        }
    
    
}









- (void)setupJPUSHWithDic:(NSDictionary *)launchOptions{

    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    BOOL isProduction = NO;
    
#if DEBUG
    isProduction = NO;
#else
    isProduction = YES;
#endif
    
    
    
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    
    
    
    
    //2.1.9版本新增获取registration id block接口。
    MJWeakSelf;
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            
            NSLog(@"registrationID获取成功：%@",registrationID);
            
            if (myViewModel.userIsLogin) {
                [weakSelf setupJpushUser];
            }
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    
}





- (void)setupJpushUser{
    
    [JPUSHService setTags:[NSSet setWithObject:@"feifubao"] completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
        
        NSLog(@"%ld++++++",(long)iResCode);
        
    } seq:myViewModel.user.user_tel.integerValue];
    
    
    [JPUSHService setAlias:myViewModel.user.uid completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
        NSLog(@"%ld+++++++",(long)iResCode);
        
        
    } seq:myViewModel.user.user_tel.integerValue + 1];
    
}





- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if ([WXApi handleOpenURL:url delegate:self]) {
        
        NSLog(@"wxapifdsfdsfdsf");
        
        return YES;
    }
    
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
            NSLog(@"%@",resultDic[@"resultStatus"]);

            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                
                [[NSNotificationCenter defaultCenter]postNotificationName:AlipayDidSuccessNotification object:nil userInfo:nil];

            } else {
                [[NSNotificationCenter defaultCenter]postNotificationName:AlipayDidFailNotification object:nil userInfo:nil];

            }
            

        }];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    
    if ([WXApi handleOpenURL:url delegate:self]) {
        
        
        NSLog(@"wxapifdsfdsfdsf");

        
        return YES;
    }

  
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
            NSLog(@"%@",resultDic[@"resultStatus"]);
            
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                
                [[NSNotificationCenter defaultCenter]postNotificationName:AlipayDidSuccessNotification object:nil userInfo:nil];
                
            } else {
                
                [[NSNotificationCenter defaultCenter]postNotificationName:AlipayDidFailNotification object:nil userInfo:nil];
                
            }
            

            
        }];
    }
    return YES;
}


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    
    if ([WXApi handleOpenURL:url delegate:self]) {
        
        NSLog(@"wxapifdsfdsfdsf");

        
        
        
        return YES;
    }
    
    
    return YES;
    
}




//微信SDK自带的方法，处理从微信客户端完成操作后返回程序之后的回调方法,显示支付结果的
-(void)onResp:(BaseResp*)resp
{
    //启动微信支付的response
//    NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
//
//    NSLog(@"%@",payResoult);
    
    
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        switch (resp.errCode) {
            case WXSuccess:
//                payResoult = @"支付成功！";
                [[NSNotificationCenter defaultCenter]postNotificationName:WXApiDidSuccessNotification object:nil userInfo:nil];
                
                break;
            case WXErrCodeCommon:
                [[NSNotificationCenter defaultCenter]postNotificationName:WXApiDidFailNotification object:nil userInfo:nil];
                break;
            case WXErrCodeUserCancel:
                [[NSNotificationCenter defaultCenter]postNotificationName:WXApiDidFailNotification object:nil userInfo:nil];
                break;
            default:
                [[NSNotificationCenter defaultCenter]postNotificationName:WXApiDidFailNotification object:nil userInfo:nil];
                break;
        }
    }
}







// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
   
    
    
    
  
    [JPUSHService registerDeviceToken:deviceToken];
}



// APP进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}

// APP将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    
}


// 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"注册deviceToken失败 -- %@",error);
}


// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSLog(@"9999999999999");
    
//
    
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"qianTaiDidReceiveNotification" object:nil];
    
    
    BaseTabBarController *tab = (BaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    if (tab.childViewControllers.count > 0) {
        
        BaseNavigationController *nav = (BaseNavigationController *)tab.childViewControllers[0];
        
        HomeViewController *homeVC = (HomeViewController *)nav.childViewControllers[0];
        
        [homeVC cancelRedDian];
    }

    
    
    
   
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"qianTaiDidReceiveNotification" object:nil];
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if (@available(iOS 10.0, *)) {
        
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
        
    } else {
        
        // Fallback on earlier versions
    }
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    } // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
//#ifdef NSFoundationVersionNumber_iOS_10_x_Max
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    
    NSLog(@"8888888888888888");

    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    completionHandler();  // 系统要求执行这个方法
    
    if (userInfo) {
        
         [self seletPushVC];
    }
}
//#endif


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"777777777777777");

    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    
    if (userInfo) {
        //        self.userInfo = userInfo;
        
        [self  seletPushVC];
        
    }
    

}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    NSLog(@"66666666666666666666");

    [JPUSHService handleRemoteNotification:userInfo];
    
    
    
    if (userInfo) {
        //        self.userInfo = userInfo;
        
        [self  seletPushVC];
        
    }
    
    
}


- (void)seletPushVC{
    
    
    if (self.tag == 1) {
        
        self.tag = 0;
        
        return;
    }
    
    
    BaseTabBarController *tab = (BaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    if (tab.childViewControllers.count > 0) {
        
        BaseNavigationController *nav = (BaseNavigationController *)tab.childViewControllers[0];
        
        HomeViewController *homeVC = (HomeViewController *)nav.childViewControllers[0];
        
        [homeVC cancelRedDian];
    }

    
    if (myViewModel.userIsLogin) {
        
        BaseTabBarController *tab = (BaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        
        if (tab.viewControllers[tab.selectedIndex].childViewControllers.count > 1) {
            
            [tab.viewControllers[tab.selectedIndex] popToRootViewControllerAnimated:NO];
            
           
            
        }
        
        MyMessageListVC *mess = [[MyMessageListVC alloc]init];
        
        [tab.viewControllers[tab.selectedIndex] pushViewController:mess animated:YES];
        
    }
  
    
}


















- (void)applicationWillResignActive:(UIApplication *)application {
  
    
    [[UserViewModel shareUserViewModel].shopCar saveUserInfo];
    [[UserViewModel shareUserViewModel].searchHistory saveHistoryInfo];

    
}

- (void)fdsfdsfdsfdsf{
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"Callback/aliPayBack" parameters:nil completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            NSLog(@"%@",responseObject);
            
        }else{
            
            [SVProgressHUD showWithStatus:error.domain];
        }
        
    }];
    
    
    
}




- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}







@end
